package servlet;

import javax.servlet.*;
import java.io.IOException;

/**
 * Author:shixiaojun@itany.com
 * Date:2022/4/11 14:43
 * Version:1.0-SNAPSHOT
 * Description:
 */
public class LifeServlet implements Servlet {

    private transient ServletConfig config;

    /**
     * 初始化方法
     * @param config
     * @throws ServletException
     */
    @Override
    public void init(ServletConfig config) throws ServletException {
        System.out.println("**************LifeServlet.init**************");
        // 根据指定的key获取对应的初始化参数的值
        // key对应的是param-name的配置
        // 返回值对应的是param-value的配置
//        String username = config.getInitParameter("username");
//        String password = config.getInitParameter("password");
//        System.out.println("username:"+username+",password:"+password);
        this.config = config;

    }

    @Override
    public ServletConfig getServletConfig() {
        return config;
    }

    public String getInitParameter(String key){
        return getServletConfig().getInitParameter(key);
    }

    /**
     * 执行核心业务逻辑
     * @param servletRequest
     * @param servletResponse
     * @throws ServletException
     * @throws IOException
     */
    @Override
    public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
        System.out.println("LifeServlet.service");
        // 方法一:通过全局变量定义ServletConfig
        String username = config.getInitParameter("username");
        String password = config.getInitParameter("password");
        System.out.println("username:"+username+",password:"+password);
        System.out.println("---------------------------------");

        // 方法二:类似于GenericServlet的处理方式
        // 自定义一个用于获取初始化参数的方法
        String username2 = getInitParameter("username");
        String password2 = getInitParameter("password");
        System.out.println("username:"+username2+",password:"+password2);
    }

    @Override
    public String getServletInfo() {
        return null;
    }

    @Override
    public void destroy() {
        System.out.println("LifeServlet.destroy");
    }
}
